package com.qpx.eurekajpa.service;

import com.qpx.dto.UserDto;
import com.qpx.eurekajpa.dao.UserDao;
import com.qpx.eurekajpa.entity.UserEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserService {

    @Autowired
    UserDao userDao;

    public Page<UserEntity> findAll(UserDto userDto){

        PageRequest of = PageRequest.of((userDto.getPageNo() - 1), userDto.getPageSize(), Sort.Direction.DESC,"id");
        Specification<UserEntity> specification = new Specification<UserEntity>() {
            @Override
            public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotBlank(userDto.getUsername())){
                    Predicate username = criteriaBuilder.equal(root.get("username"), userDto.getUsername());
                    predicates.add(username);
                }
                if (StringUtils.isNotBlank(userDto.getName())){
                    Predicate name = criteriaBuilder.like(root.get("name"), "%"+userDto.getName()+"%");
                    predicates.add(name);
                }
                if (userDto.getSex()!=null){
                    Predicate name = criteriaBuilder.ge(root.get("sex"), userDto.getSex());
                    predicates.add(name);
                }
                if (StringUtils.isNotBlank(userDto.getStartTime())&&StringUtils.isNotBlank(userDto.getEndTime())){
                    try {
                        Date beginTime = DateUtils.parseDate(userDto.getStartTime() + " 00:00:00","yyyy-MM-dd HH:mm:ss");
                        Date endTime = DateUtils.parseDate(userDto.getEndTime()+" 23:59:59","yyyy-MM-dd HH:mm:ss");
                        Predicate createTime = criteriaBuilder.between(root.get("createTime"), beginTime, endTime);
                        predicates.add(createTime);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        return userDao.findAll(specification,of);
    }
}
